package application.dispatcher;

import java.io.IOException;
import java.sql.SQLException;

import javax.servlet.ServletException;

import org.dsrg.soenea.domain.command.CommandException;
import org.dsrg.soenea.domain.mapper.DomainObjectNotFoundException;

import domain.command.LoginCommand;
import domain.model.user.User;
import domain.model.user.mapper.UserInputMapper;

public class LoginDispatcher extends Dispatcher 
{

	@Override
	public void execute() throws ServletException, IOException 
	{
		//if the user is already logged in then he gets sent to the browse group page, else he can log in
		if(myHelper.getSessionAttribute("userid") != null)
		{
			//forward("/GroupFormationSoftware?dispatcher=application.dispatcher.BrowseGroupsDispatcher");
			//forward("/GroupFormationSoftware/browsegroups/");
			
				relativeRedirect("browsegroups");
			
			
		}
		else //user not logged in so proceed to authenticate...
		{
			try 
			{
				new LoginCommand(myHelper).execute();
				//forward("/GroupFormationSoftware?dispatcher=application.dispatcher.BrowseGroupsDispatcher");
				//forward("/GroupFormationSoftware/browsegroups/");
				
				
				//After logging in, he gets sent to his group page if in a group, or the browse group page
				User user = null;
				try {
					user = UserInputMapper.find((Long)(myHelper.getSessionAttribute("userid")));
				} catch (DomainObjectNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
				if(user.getGroup().getId() != 0) // if the user is in a group
				{
					relativeRedirect("viewgroup");
				}
				else
				{
					relativeRedirect("browsegroups");
				}
				
			} 
			catch (CommandException e) 
			{
				// login failed
				myRequest.setAttribute("msg", "Invalid username/password combination ");
				forward("/WEB-INF/JSP/home.jsp");
			}
		}
	}
}